package com.lvhengchang.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lvhengchang.mapper.UserMapper;
import com.lvhengchang.pojo.User;
import com.lvhengchang.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public List<User> selectUserList() {
		return userMapper.selectUserList();
	}

	@Override
	@Transactional(rollbackFor = { IllegalArgumentException.class })
	public int deleteUser(int id) {
		return userMapper.deleteUser(id);
	}

	@Override
	@Transactional(rollbackFor = { IllegalArgumentException.class })
	public int insertUser(User user) throws Exception {
		List<User> lst = userMapper.selectUserList();
		for (int j = 0; j < lst.size(); j++) {
			String name = lst.get(j).getUserName();
			if (user.getUserName().equals(name)) {
				throw new IllegalArgumentException("LHC已存在，数据将回滚");
			}
		}
		int r = userMapper.insertUser(user);
		if (r != 0) {
			return r;
		} else {
			throw new RuntimeException("用户添加异常");
		}
	}

	@Override
	@Transactional(rollbackFor = { IllegalArgumentException.class })
	public int updateById(User user) {
		return userMapper.updateUser(user);
	}

	@Override
	public User getUserById(int id) {
		return userMapper.selectByUserId(id);
	}

}
